package com.immunology.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.immunology.logic.security.SecurityService;
import com.immunology.logic.validators.LoginFieldValidator;
import com.immunology.model.AttributeContent;
import com.immunology.model.MappingPages;
import com.immunology.model.User;
import com.immunology.model.enums.Role;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		User user = null;
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		SecurityService securityService = new SecurityService();

		boolean isValidLogin = new LoginFieldValidator().isLoginInDB(login);
		if (isValidLogin) {
			user = securityService.getUser(login, password);
		}

		if (user != null) {
			request.getSession().setAttribute(AttributeContent.USER, user);
			if (user.getRole() == Role.ADMIN) {
				response.sendRedirect(MappingPages.ADMIN_PAGE);
			} else if (user.getRole() == Role.USER) {
				response.sendRedirect(MappingPages.USER_PAGE + user.getId());
			}
		} else {
			getServletContext().setAttribute(AttributeContent.ERROR_LOGIN,
					"Wrong login or password");
			getServletContext().getRequestDispatcher(MappingPages.LOGIN_JSP)
					.forward(request, response);
			getServletContext().removeAttribute(AttributeContent.ERROR_LOGIN);
		}

	}
}
